package com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;


import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import auth.ParseXML;

/**
 * Servlet implementation class HelloServlet
 */
public class Connect extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
       
	
	final String CAS_BASE = "https://sso-cas.univ-lille1.fr";
	final String SERVICE = "http://localhost:8080/pji/Connect";
	
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Connect() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String ticket;
		@SuppressWarnings("rawtypes")
		Enumeration tab = request.getParameterNames();
		boolean contains = false;
		
		while(tab.hasMoreElements())
			if(tab.nextElement().equals("ticket")){
				contains = true;
				break;
			}
		
		if(!contains){
			System.out.println("Redirection");
			response.sendRedirect(CAS_BASE +"/login?service=" + SERVICE);
		}
		else
		{
			System.out.println("Validation du ticket");
			ticket = request.getParameter("ticket");
			String url_validate = CAS_BASE + "/serviceValidate"+"?service=" + SERVICE + "&ticket=" + ticket;
		
			
			URL url = new URL(url_validate);
			BufferedReader br = new BufferedReader( new InputStreamReader(url.openStream()));
			
		
			String chaine = "";
			boolean log = false;
			String buf;
			while((buf = br.readLine()) != null){
				chaine.concat(buf);
			}
			
			System.out.println(chaine);
			
			ParseXML p = new ParseXML(chaine);
			System.out.println("uid " + p.getUID());
			
			if(log){
				HttpSession session = request.getSession();
				session.setAttribute("login", "texte");
			}
			
/*			PrintWriter out = response.getWriter();
			response.setContentType("text/html");
			out.println("<head><title>Hello</title></head>");		
			out.println("<body>");
			out.println("</body>");
*/		
		}		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
